//
//  MediaDetailViewController.m
//  LegalObserver
//
//  Created by Roxanne Brittain on 11/1/11.
//  Copyright (c) 2011 Digifit. All rights reserved.
//

#import "MediaDetailViewController.h"
#import "LOAppDelegate.h"
#import "LOTableViewCell.h"
#import <QuartzCore/QuartzCore.h>

#define SECTION_ID_GENERAL_INFO 0
#define SECTION_ID_NOTES        1
#define SECTION_ID_EMAIL        2

@implementation MediaDetailViewController
@synthesize media, moviePlayerController;

- (id)initWithMediaIndex:(int)i
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {
        // Custom initialization
        mediaIndex = i;
        self.title = @"Media Details";
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView
 {
 }
 */

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    mediaArray = [LOAppDelegate getMediaArray];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 301, 234)];
    mediaView = [[UIView alloc] initWithFrame:CGRectMake(10, 9, 301, 225)];
    imageView = [[UIImageView alloc] initWithFrame:mediaView.bounds];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.backgroundColor = [UIColor whiteColor];
    imageView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    imageView.layer.borderWidth = 1;
    [mediaView addSubview:imageView];
    [view addSubview:mediaView];
    [self.tableView setTableHeaderView:view];
    
    [self displayMedia];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(onDoneButton:)];
    
    UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"rightarrow.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onRightButton:)];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"leftarrow.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onLeftButton:)];
    UIBarButtonItem *trashButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(onTrashButton:)];
    self.toolbarItems = [NSArray arrayWithObjects:spacer, leftButton, spacer, rightButton, spacer, trashButton, nil];
    self.navigationController.toolbarHidden = NO;
}

-(void)displayMedia
{
    media = [mediaArray objectAtIndex:mediaIndex];
    if (media.type == MEDIA_TYPE_PHOTO) {
        imageView.image = media.image;
        [moviePlayerController.view setHidden:YES];
        [moviePlayerController stop];
    } else {
        imageView.image = nil;
        [self createAndPlayMovieForURL:media.videoURL sourceType:MPMovieSourceTypeFile];
        [moviePlayerController.view setHidden:NO];
    }
}

-(void)createAndConfigurePlayerWithURL:(NSURL *)movieURL sourceType:(MPMovieSourceType)sourceType 
{    
    if (!moviePlayerController)
        moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
    
    if (moviePlayerController) {
        
        [moviePlayerController setContentURL:movieURL];        
        
        [moviePlayerController setMovieSourceType:sourceType];
        
        NSLog(@"mv: %@", mediaView);
        [[moviePlayerController view] setFrame:CGRectMake(0, 0, mediaView.frame.size.width, mediaView.frame.size.height)];
        NSLog(@"->mp vw: %@", moviePlayerController.view);
        
        [moviePlayerController setScalingMode:MPMovieScalingModeAspectFit];
        [moviePlayerController view].backgroundColor = [UIColor whiteColor];
        [moviePlayerController backgroundView].backgroundColor = [UIColor whiteColor];
        [moviePlayerController view].layer.borderWidth = 1;
        [moviePlayerController view].layer.borderColor = [UIColor lightGrayColor].CGColor;
        
        [mediaView addSubview: [moviePlayerController view]];        
    } 
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieDurationAvailable:) name:MPMovieDurationAvailableNotification object:nil];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMovieDurationAvailableNotification object:nil];
}

-(void)movieDurationAvailable:(NSNotification*)notification
{
    if (media.duration==0) 
        media.duration = moviePlayerController.duration;
}

/* Load and play the specified movie url with the given file type. */
-(void)createAndPlayMovieForURL:(NSURL *)movieURL sourceType:(MPMovieSourceType)sourceType
{
    [self createAndConfigurePlayerWithURL:movieURL sourceType:sourceType];
    
    [[self moviePlayerController] play];
}

-(void)onDoneButton:(id)sender
{
    [moviePlayerController stop];
    moviePlayerController = nil;
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 40,20)];
    UIBarButtonItem *activityItem = [[UIBarButtonItem alloc] initWithCustomView:activityIndicator];
    activityItem.style = UIBarButtonItemStyleBordered;
    self.navigationItem.rightBarButtonItem = activityItem;
    [activityIndicator startAnimating];
    
    [NSThread detachNewThreadSelector:@selector(saveAndDismiss) toTarget:self withObject:nil];
}

-(void)onTrashButton:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Delete Media" otherButtonTitles: nil];
    [actionSheet showFromToolbar:self.navigationController.toolbar];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0) [self deleteMedia];
}

-(void)deleteMedia
{
    [mediaArray removeObjectAtIndex:mediaIndex];
    [self onLeftButton:nil];
}

-(void)saveAndDismiss
{
    [LOAppDelegate saveMediaArray:mediaArray];
    [self dismissModalViewControllerAnimated:YES];
}

-(void)onRightButton:(id)sender
{
    mediaIndex++;
    mediaIndex%=[mediaArray count];
    [self displayMedia];
    [self.tableView reloadData];
    
    //    [LOAppDelegate saveMediaArray:mediaArray];
}

-(void)onLeftButton:(id)sender
{
    mediaIndex--;
    mediaIndex=(mediaIndex+[mediaArray count])%[mediaArray count];
    [self displayMedia];
    [self.tableView reloadData];
    
    //    [LOAppDelegate saveMediaArray:mediaArray];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 3;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section==SECTION_ID_GENERAL_INFO) return @"";
    else if (section==SECTION_ID_NOTES) return @"Notes";
    
    return @"";
}

-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    if (section==SECTION_ID_GENERAL_INFO) return @"";
    else if (section==SECTION_ID_NOTES) return @"";
    
    return @"";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (section==SECTION_ID_GENERAL_INFO) return 3;
    else if (section==SECTION_ID_NOTES) return 1;
    else if (section==SECTION_ID_EMAIL) return 1;
    
    return 0;
}

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==SECTION_ID_NOTES) return 100;
    else return 45;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    int style = UITableViewCellStyleDefault;
    if (indexPath.section == SECTION_ID_GENERAL_INFO) style = TABLE_CELL_STYLE_FORM;
    else if (indexPath.section == SECTION_ID_NOTES) style = TABLE_CELL_STYLE_NOTE;
    else if (indexPath.section == SECTION_ID_EMAIL) style = TABLE_CELL_STYLE_BUTTON;

    LOTableViewCell *cell = nil;//[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[LOTableViewCell alloc] initWithStyle:style reuseIdentifier:CellIdentifier];
        cell.object = media;
    }
        
    if (indexPath.section==SECTION_ID_GENERAL_INFO) {
        if (indexPath.row==0) {
            cell.titleLabel.text = @"Title";
            cell.textField.placeholder = @"Title";
            cell.textField.text = media.title;
            cell.key = @"title";
        } else if (indexPath.row==1) {
            cell.titleLabel.text = @"Date";
            cell.textField.placeholder = @"Date";
            cell.textField.text = [LOAppDelegate stringFromDate:media.dateCreated];
            //            cell.textField.enabled = NO;
            cell.key = @"dateCreated";
            cell.showTime = YES;
            cell.isDate = YES;
        } else if (indexPath.row==2) {
            cell.titleLabel.text = @"Location";
            cell.textField.placeholder = @"Location";
            cell.textField.text = media.location;
            cell.key = @"location";
        }
    } else if (indexPath.section==SECTION_ID_NOTES) {
        cell.textView.text = media.notes;
        cell.key = @"notes";
    } else if (indexPath.section==SECTION_ID_EMAIL) {
        cell.textLabel.text = @"Email Media & Info";
    }
    
    return cell;
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    
    [(LOTableViewCell*)[tableView cellForRowAtIndexPath:indexPath] didSelectCell];
    
    if (indexPath.section==SECTION_ID_EMAIL) {
        MFMailComposeViewController *vc = [LOAppDelegate backupMedia:media];
        vc.mailComposeDelegate = self;
        [self presentModalViewController:vc animated:YES];
    }
}


-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    [self dismissModalViewControllerAnimated:YES];
}

@end
